package com.learn.security.service;

import com.learn.security.entity.AdminEntity;
import com.learn.security.entity.RoleEntity;
import com.learn.security.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class AuthService implements AuthenticationProvider {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AdminRepository adminRepository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        AdminEntity adminEntity =   adminRepository.findByName(username);
        if(adminEntity == null){
            throw new BadCredentialsException("Username not found.");
        }

        String token    =   adminEntity.getToken();
        String md5Password  =   DigestUtils.md5DigestAsHex((password+token).getBytes());

        //加密过程在这里体现
        if (!md5Password.equals(adminEntity.getPassword())) {
            throw new BadCredentialsException("Wrong password.");
        }

        List<RoleEntity> roleEntityList = roleService.roleEntityList(adminEntity.getRoleId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for(RoleEntity role:roleEntityList)
        {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new UsernamePasswordAuthenticationToken(username, md5Password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

}
